import 'package:aweb5/generated/json/common_result_entity_helper.dart';
import 'package:aweb5/generated/json/upload_entity_helper.dart';
import 'package:aweb5/util/DateUtil.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:aweb5/Para.dart';
import 'package:aweb5/util/NaviUtil.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:bubble/bubble.dart';

import 'package:image_picker/image_picker.dart';
import 'package:image_picker/image_picker.dart';
import 'package:video_player/video_player.dart';
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:aweb5/bean/detail_temp.dart';
import 'package:aweb5/pages/input_page.dart';
import 'package:aweb5/pages/video_page.dart';
import 'package:aweb5/pages/PhotoViewGalleryScreen.dart';
import 'package:load/load.dart';
import 'package:aweb5/Constants.dart';
import 'package:aweb5/util/HttpClient.dart';
import 'package:aweb5/util/toast_util.dart';
import 'package:aweb5/config/Config.dart';
import 'package:aweb5/bean/aplus/common_result_entity.dart';
import 'package:aweb5/util/NaviUtil.dart';
import 'package:aweb5/util/DialogUtil.dart';
import 'package:aweb5/style.dart';
import 'product_list.dart';
import 'package:aweb5/pages/product_list.dart';
import 'package:aweb5/widgetlib/menu_widget.dart';
import 'package:aweb5/bean/aplus/group_plan_list_entity.dart';
import 'package:video_player/video_player.dart';
import 'package:aweb5/bean/aplus/material_type_entity.dart';
import 'package:aweb5/generated/json/material_type_entity_helper.dart';
import 'package:aweb5/bean/aplus/jjhw_product_list_entity.dart';
import 'package:aweb5/util/BussinussUtil.dart';
import 'package:aweb5/util/HttpUtils1.dart';
import 'package:aweb5/bean/aplus/upload_entity.dart';
import 'package:aweb5/custombean/download_bean.dart';
import 'package:permission_handler/permission_handler.dart';

import 'package:aweb5/util/PermissionUtil.dart';
import 'package:aweb5/util/FileUtil.dart';
import 'package:progress_dialog/progress_dialog.dart';
import 'package:flutter/services.dart';
class PlanDetail extends StatefulWidget {
  List<GroupPlanListDataTimeDataTaskSendInfo> info = null;
//  GroupPlanListDataMember groupPlanListDataMember = null;
  GroupPlanListDataFollow followdata = null;
  String title;
  String url;
  ///是否是从素材库的
//  String sendId;
  String from;
  PlanDetail(this.info, this.followdata,this.title,{this.url,this.from});

  @override
  _PlanDetailState createState() => _PlanDetailState();
}

class _PlanDetailState extends State<PlanDetail> {
  bool isVideo;
//  VideoPlayerController _controller;
  VideoPlayerController _toBeDisposed;
//  List<DetailTemp> list = [];
  final ImagePicker _picker = ImagePicker();
//  PickedFile _imageFile;
  bool show = true;
  List<String> images = List();

  BuildContext context;
  List<DropdownMenuItem<String>> sortItems = [];
  String _selectedSort = '排序';

  String title = "";
  List<Download> downloadList = List();
  @override
  void initState() {
    super.initState();
    if(widget.info==null){
      widget.info = List();
    }
    sortItems.add(DropdownMenuItem(value: '排序', child: Text('排序')));
    sortItems.add(DropdownMenuItem(value: '价格降序', child: Text('价格降序')));
    sortItems.add(DropdownMenuItem(value: '价格升序', child: Text('价格升序')));
//    list.add(DetailTemp("text", "呵呵哒", "0"));
//    list.add(DetailTemp("text", "呵呵哒呵呵呵呵呵呵额呵呵呵呵呵呵呵呵呵", "1"));
//    list.add(DetailTemp(
//        "image",
//        "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1595999389419&di=a3fefdffae6c3c8380f1fd2b2c1570fc&imgtype=0&src=http%3A%2F%2Fs7.rr.itc.cn%2Fg%2FwapChange%2F20154_27_12%2Fa81bal5437342566667.JPEG",
//        "2"));
//    list.add(DetailTemp(
//        "image",
//        "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1595999389420&di=6a0a4bf60da02c553e3c63081428c0af&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201812%2F29%2F20181229105534_iyfyt.jpg",
//        "3"));
//    list.add(DetailTemp(
//        "video", "https://www.runoob.com/try/demo_source/mov_bbb.mp4", "4"));
    for (int i = 0; i < widget.info.length; i++) {
//    for (GroupPlanListDataTimeDataTaskSendInfo info in widget.info) {

      widget.info[i].index = i;

      if (widget.info[i].type == 2) {
        if (widget.info[i].data.startsWith("http")) {
          widget.info[i].setController(
              VideoPlayerController.network(widget.info[i].data));
        } else {
          widget.info[i].setController(
              VideoPlayerController.file(File(widget.info[i].data)));
        }
      }

      if (widget.info[i].type == 1) {
        images.add(widget.info[i].data);
      }
    }

//    _controller = VideoPlayerController.network(
//        "https://www.runoob.com/try/demo_source/mov_bbb.mp4")
//      ..initialize().then((_) {
//        // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
//        setState(() {});
//      });



  }

  @override
  Widget build(BuildContext context) {
    this.context = context;
    initDialog(context);
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Color(0xfff8f8f8),
        leading: GestureDetector(
          child: Container(
            alignment: Alignment.center,
            width: ScreenUtil().setWidth(39),
            height: ScreenUtil().setHeight(39),
            child: Image.asset(
              "assets/assist/back.png",
              width: ScreenUtil().setWidth(24),
              height: ScreenUtil().setHeight(24),
            ),
          ),
          onTap: () {
            NaviUtil.pop(context);
          },
        ),
        title: Text(
          "${widget.title}",
          style: TextStyle(color: Color(0xff101010), fontSize: 18),
        ),
        centerTitle: true,
//        actions: <Widget>[
//          Container(
//            width: 44,
//            height: 44,
//            child: Image.asset(
//              "assets/ab.png",
//              width: 20,
//              height: 20,
//            ),
//          )
//        ],
      ),
      body: buildBody(),
    );
  }

  Widget buildBody() {
    return Stack(
      children: <Widget>[
        ReorderableListView(
            children: widget.info.map(f).toList(),
//        header: Text('This is the header!'),
            onReorder: (oldIndex, newIndex) {
              setState(() {
                _updateMyItems(oldIndex, newIndex);
              });
            }),
        Positioned(
          child: bottomButton(),
          bottom: 6,
        )
      ],
    );
  }

  Widget bottomButton() {
    if (!show) {
      return Container(
        width: ScreenUtil().setWidth(414),
        child: SafeArea(
            child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            Flexible(
              child: GestureDetector(
                child: Center(
                  child: Container(
                    width: ScreenUtil().setWidth(61),
                    height: ScreenUtil().setWidth(61),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Image.asset(
                          "assets/assist/lianjie.png",
                          width: ScreenUtil().setWidth(20),
                          height: ScreenUtil().setWidth(20),
                        ),
                        SizedBox(
                          height: ScreenUtil().setWidth(4),
                        ),
                        Text(
                          "链接",
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: ScreenUtil().setSp(14)),
                        )
                      ],
                    ),
                    decoration: BoxDecoration(
                        color: Color(0xffF94F68),
                        borderRadius:
                            BorderRadius.circular(ScreenUtil().setWidth(31))),
                  ),
                ),
                onTap: () {
                  _showBottomSheet(true);
//                showInput(context);
                },
              ),
            ),
            Flexible(
              child: GestureDetector(
                child: Center(
                  child: Container(
                    width: ScreenUtil().setWidth(61),
                    height: ScreenUtil().setWidth(61),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Image.asset(
                          "assets/assist/qianbi.png",
                          width: ScreenUtil().setWidth(20),
                          height: ScreenUtil().setWidth(20),
                        ),
                        SizedBox(
                          height: ScreenUtil().setWidth(4),
                        ),
                        Text(
                          "文字",
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: ScreenUtil().setSp(14)),
                        )
                      ],
                    ),
                    decoration: BoxDecoration(
                        color: Color(0xffF94F68),
                        borderRadius:
                            BorderRadius.circular(ScreenUtil().setWidth(31))),
                  ),
                ),
                onTap: () {
//                NaviUtil.push(context,InputPage() );
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (c) {
                    return InputPage();
                  })).then((value) {
                    GroupPlanListDataTimeDataTaskSendInfo info =
                        GroupPlanListDataTimeDataTaskSendInfo();
                    info.type = 3;
                    info.data = (value as String);
                    int temp = 0;
                    for (int i = 0; i < widget.info.length; i++) {
                      if (widget.info[i].index > temp) {
                        temp = widget.info[i].index;
                      }
                    }
                    info.index = temp + 1;
                    widget.info.add(info);
//                    if ((value as String).isNotEmpty) {
//                      list.add(DetailTemp(
//                          "text", (value as String), list.length.toString()));
//                    }
                    setState(() {});
                  });
//                showInput(context);
                },
              ),
            ),
            Flexible(
                child: GestureDetector(
              child: Center(
                child: Container(
                  width: ScreenUtil().setWidth(61),
                  height: ScreenUtil().setWidth(61),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image.asset(
                        "assets/assist/tupian.png",
                        width: ScreenUtil().setWidth(20),
                        height: ScreenUtil().setWidth(20),
                      ),
                      SizedBox(
                        height: ScreenUtil().setWidth(4),
                      ),
                      Text(
                        "图片",
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: ScreenUtil().setSp(14)),
                      )
                    ],
                  ),
                  decoration: BoxDecoration(
                      color: Color(0xffF94F68),
                      borderRadius:
                          BorderRadius.circular(ScreenUtil().setWidth(31))),
                ),
              ),
              onTap: () {
                this.isVideo = false;
                _onImageButtonPressed(ImageSource.gallery, context: context);
              },
            )),
            Flexible(
                child: GestureDetector(
              child: Center(
                child: Container(
                  width: ScreenUtil().setWidth(61),
                  height: ScreenUtil().setWidth(61),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image.asset(
                        "assets/assist/shipin.png",
                        width: ScreenUtil().setWidth(20),
                        height: ScreenUtil().setWidth(20),
                      ),
                      SizedBox(
                        height: ScreenUtil().setWidth(4),
                      ),
                      Text(
                        "视频",
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: ScreenUtil().setSp(14)),
                      )
                    ],
                  ),
                  decoration: BoxDecoration(
                      color: Color(0xffF94F68),
                      borderRadius:
                          BorderRadius.circular(ScreenUtil().setWidth(31))),
                ),
              ),
              onTap: () {
                this.isVideo = true;
                _onImageButtonPressed(ImageSource.gallery, context: context);
              },
            )),
            Flexible(
                child: GestureDetector(
              child: Center(
                child: Container(
                  width: ScreenUtil().setWidth(61),
                  height: ScreenUtil().setWidth(61),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image.asset(
                        "assets/assist/tuichu.png",
                        width: ScreenUtil().setWidth(20),
                        height: ScreenUtil().setWidth(20),
                      ),
                      SizedBox(
                        height: ScreenUtil().setWidth(4),
                      ),
                      Text(
                        "退出",
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: ScreenUtil().setSp(14)),
                      )
                    ],
                  ),
                  decoration: BoxDecoration(
                      color: Color(0xffF94F68),
                      borderRadius:
                          BorderRadius.circular(ScreenUtil().setWidth(31))),
                ),
              ),
              onTap: () {
                show = true;
                setState(() {});
              },
            )),
          ],
        )),
      );
    } else {
      return SafeArea(
          child: Container(
        height: ScreenUtil().setHeight(41),
        width: ScreenUtil().setWidth(414),
        margin: EdgeInsets.only(bottom: ScreenUtil().setHeight(25)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
//            GestureDetector(
//              child: Container(
//                width: ScreenUtil().setWidth(126),
//                alignment: Alignment.center,
//                height: 40,
//                decoration: BoxDecoration(
//                    color: Color(0xffF94F68),
//                    borderRadius:
//                        BorderRadius.circular(ScreenUtil().setWidth(4))),
//                child: Row(
//                  mainAxisAlignment: MainAxisAlignment.center,
//                  children: <Widget>[
//                    Image.asset(
//                      "assets/ab.png",
//                      width: ScreenUtil().setWidth(24),
//                      height: ScreenUtil().setHeight(24),
//                    ),
//                    SizedBox(
//                      width: ScreenUtil().setWidth(10),
//                    ),
//                    Text(
//                      "发布",
//                      style: TextStyle(
//                          color: Colors.white,
//                          fontSize: ScreenUtil().setSp(18)),
//                    )
//                  ],
//                ),
//              ),
//              onTap: () {
//                _showChoosePost();
//              },
//            ),
            GestureDetector(
              child: Container(
//                width: ScreenUtil().setWidth(60),
                width: ScreenUtil().setWidth(100),
                height: ScreenUtil().setHeight(40),
                decoration: BoxDecoration(
                    color: Color(0xffFFE9E8),
                    border: Border.all(color: Color(0xffF94F68)),
                    borderRadius:
                        BorderRadius.circular(ScreenUtil().setWidth(4))),
                child: Text(
                  "编辑",
                  style: TextStyle(
                      color: Color(0xffF94F68),
                      fontSize: ScreenUtil().setSp(18)),
                ),
                alignment: Alignment.center,
              ),
              onTap: () {
                show = false;
                setState(() {});
              },
            ),
            GestureDetector(
              child: Container(
//                width: ScreenUtil().setWidth(60),
                width: ScreenUtil().setWidth(100),
                height: ScreenUtil().setHeight(40),
                decoration: BoxDecoration(
                    color: Color(0xffFFE9E8),
                    border: Border.all(color: Color(0xffF94F68)),
                    borderRadius:
                        BorderRadius.circular(ScreenUtil().setWidth(4))),
                child: Text(
                  "保存",
                  style: TextStyle(
                      color: Color(0xffF94F68),
                      fontSize: ScreenUtil().setSp(18)),
                ),
                alignment: Alignment.center,
              ),
              onTap: () {
                if(widget.info.length==0){
                  return;
                }
                showSaveDialog();
              },
            ),
            GestureDetector(
              child: Container(
//                width: ScreenUtil().setWidth(60),
                width: ScreenUtil().setWidth(100),
                height: ScreenUtil().setHeight(40),
                decoration: BoxDecoration(
                    color: Color(0xffFFE9E8),
                    border: Border.all(color: Color(0xffF94F68)),
                    borderRadius:
                        BorderRadius.circular(ScreenUtil().setWidth(4))),
                child: Text(
                  "下载",
                  style: TextStyle(
                      color: Color(0xffF94F68),
                      fontSize: ScreenUtil().setSp(18)),
                ),
                alignment: Alignment.center,
              ),
              onTap: () {

                _download();

              },
            ),
//            GestureDetector(
//              child: Container(
//                width: ScreenUtil().setWidth(60),
//                height: ScreenUtil().setHeight(40),
//                decoration: BoxDecoration(
//                    color: Color(0xffCBFFB9),
//                    border: Border.all(color: Color(0xff00C91E)),
//                    borderRadius:
//                        BorderRadius.circular(ScreenUtil().setWidth(4))),
//                child: Text(
//                  "分享",
//                  style: TextStyle(
//                      color: Color(0xff00C91E),
//                      fontSize: ScreenUtil().setSp(18)),
//                ),
//                alignment: Alignment.center,
//              ),
//              onTap: () {},
//            )
          ],
        ),
      ));
    }
  }
  initDialog(BuildContext context) {
    pr = ProgressDialog(
      context,
      type: ProgressDialogType.Download,
      textDirection: TextDirection.rtl,
      isDismissible: true,

    );

    pr.style(
//      message: 'Downloading file...',
      message: "请稍候……",
      borderRadius: 10.0,
      backgroundColor: Colors.white,
      elevation: 10.0,
      insetAnimCurve: Curves.easeInOut,
      progress: 0.0,
      progressWidgetAlignment: Alignment.center,
      maxProgress: 100.0,
      progressTextStyle: TextStyle(
          color: Colors.black, fontSize: 13.0, fontWeight: FontWeight.w400),
      messageTextStyle: TextStyle(
          color: Colors.black, fontSize: 19.0, fontWeight: FontWeight.w600),
    );
  }
  void downloadCallBack() {

    pr.hide();


  }
  void copyFirst(){

    for(int i=0;i<widget.info.length;i++){

      if(widget.info[i].type==3){

        ClipboardData data = ClipboardData(text: widget.info[i].data);
        Clipboard.setData(data);

        Toast.show(msg: "第一段文案已复制");

        break;

      }

    }

  }
  List<String> path = List();
  List<bool> finishNum = List();
  ProgressDialog pr;
  void _download() async{
    pr.show();
    path.clear();
    finishNum.clear();
    downloadList.clear();
    buildDownLoadList();

    if(Platform.isAndroid){

      PermissionStatus status =
      await PermissionUtil.requestPermission(Permission.storage);
      if(status==PermissionStatus.granted){
        String basicpath = (await FileUtil.findLocalPath(context)) +
            Constants.packagesavePath+
//          Platform.pathSeparator +"${DateTime.now().year+DateTime.now().month+DateTime.now().day}"+DateTime.now().millisecond.toString();
            Platform.pathSeparator +"${DateUtil.formatDateTimeToString(DateTime.now()).replaceAll("-", "")}";
        final savedDir = Directory(basicpath);
        bool hasExisted = await savedDir.exists();
        if (!hasExisted) {
          savedDir.create();
        }
        int downloadNum = downloadList.length;
        if(downloadNum ==null||downloadNum==0){

          return;
        }
        copyFirst();
        for (int i = 0; i < downloadList.length; i++) {
          HttpUtils.downloadMultiFile(
              downloadList[i].url,
              basicpath +
                  "/${DateTime.now().millisecondsSinceEpoch}x${i}x.jpg",
              path,
              finishNum,
              downloadCallBack,
              downloadNum,
              pr,i);
        }
      }


    }else{

      String basicpath = (await FileUtil.findLocalPath(context)) +
          Constants.packagesavePath+
//          Platform.pathSeparator +"${DateTime.now().year+DateTime.now().month+DateTime.now().day}"+DateTime.now().millisecond.toString();
          Platform.pathSeparator +"${DateUtil.formatDateTimeToString(DateTime.now()).replaceAll("-", "")}";
      final savedDir = Directory(basicpath);
      bool hasExisted = await savedDir.exists();
      if (!hasExisted) {
        savedDir.create();
      }
      int downloadNum = downloadList.length;
      if(downloadNum ==null||downloadNum==0){

        return;
      }
      copyFirst();
      for (int i = 0; i < downloadList.length; i++) {
        HttpUtils.downloadMultiFile(
            downloadList[i].url,
            basicpath +
                "/${DateTime.now().millisecondsSinceEpoch}x${i}x.jpg",
            path,
            finishNum,
            downloadCallBack,
            downloadNum,
            pr,i);
      }

    }




  }

  int indexInListView = 0;
  void _updateMyItems(int oldIndex, int newIndex) {
    var tmp = widget.info[oldIndex];
    if (newIndex < oldIndex) {
      widget.info.removeAt(oldIndex);
      widget.info.insert(newIndex, tmp);
    } else {
      widget.info.removeAt(oldIndex);
      widget.info.insert(newIndex - 1, tmp);
    }
  }

  Widget f(GroupPlanListDataTimeDataTaskSendInfo i) {
    return typeItem(i);
  }

  void up(int index) {
    var tmp = widget.info[index];
    if (index > 0) {
      widget.info[index] = widget.info[index - 1];
      widget.info[index - 1] = tmp;
    }

    setState(() {});
  }

  void down(int index) {
    var tmp = widget.info[index];
    if (index < widget.info.length - 1) {
      widget.info[index] = widget.info[index + 1];
      widget.info[index + 1] = tmp;
    }
    setState(() {});
  }

  void delete(int index) {
    widget.info.removeAt(index);
    setState(() {});
  }

//  Future<void> _playVideo(PickedFile file) async {
//    if (file != null && mounted) {
//      await _disposeVideoController();
//      if (kIsWeb) {
//        _controller = VideoPlayerController.network(file.path);
//        // In web, most browsers won't honor a programmatic call to .play
//        // if the video has a sound track (and is not muted).
//        // Mute the video so it auto-plays in web!
//        // This is not needed if the call to .play is the result of user
//        // interaction (clicking on a "play" button, for example).
//        await _controller.setVolume(0.0);
//      } else {
//        _controller = VideoPlayerController.file(File(file.path));
//        await _controller.setVolume(1.0);
//      }
//      await _controller.initialize();
//      await _controller.setLooping(false);
//      await _controller.play();
//      setState(() {});
//    }
//  }

  Future<void> _disposeVideoController() async {
    if (_toBeDisposed != null) {
      await _toBeDisposed.dispose();
    }
//    _toBeDisposed = _controller;
//    _controller = null;
  }

  void _onImageButtonPressed(ImageSource source, {BuildContext context}) async {
//    if (_controller != null) {
//      await _controller.setVolume(0.0);
//    }
    if (isVideo) {
      final PickedFile file = await _picker.getVideo(
        source: source,
      );
//      Fluttertoast.showToast(msg: "${file.path}", textColor: Colors.black);

      requestUpload(File(file.path), false);
//      GroupPlanListDataTimeDataTaskSendInfo info =
//          GroupPlanListDataTimeDataTaskSendInfo();
//      info.data = file.path;
//      info.type = 2;
//      int temp = 0;
//      for (int i = 0; i < widget.info.length; i++) {
//        if (widget.info[i].index > temp) {
//          temp = widget.info[i].index;
//        }
//      }
//      info.index = temp + 1;
//      info.setController(VideoPlayerController.file(File(file.path)));
//
//      widget.info.add(info);

//      widget.info.add(GroupPlanListDataTimeDataTaskSendInfo("video", file.path, list.length.toString())
//          .setController(VideoPlayerController.file(File(file.path))));
//      await _playVideo(file);
    } else {
      try {
        final pickedFile = await _picker.getImage(
          source: source,
        );

        requestUpload(File(pickedFile.path), true);


//        GroupPlanListDataTimeDataTaskSendInfo info =
//            GroupPlanListDataTimeDataTaskSendInfo();
//        info.type = 1;
//        info.data = pickedFile.path;
//        int temp = 0;
//        File  f = File(pickedFile.path);
//        for (int i = 0; i < widget.info.length; i++) {
//          if (widget.info[i].index > temp) {
//            temp = widget.info[i].index;
//          }
//        }
//        info.index = temp + 1;
//        widget.info.add(info);
//        list.add(DetailTemp("image", pickedFile.path, list.length.toString()));
//        Fluttertoast.showToast(
//            msg: "${pickedFile.path}", textColor: Colors.black);
        setState(() {
//          _imageFile = pickedFile;
        });
//        HttpUtils.upload(f, true);
      } catch (e) {
        setState(() {});
      }
    }
    setState(() {});
  }

  showInput(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (con) {
          return Container(
            width: ScreenUtil().setWidth(414),
            height: ScreenUtil().setHeight(414),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
                border: Border.all(color: Colors.grey)),
            child: TextField(
              decoration: InputDecoration(
                hintText: "请输入",
                hintStyle: TextStyle(color: Colors.grey),
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5.0),
                    borderSide: BorderSide()),
              ),
            ),
          );
        });
  }

  Widget typeItem(GroupPlanListDataTimeDataTaskSendInfo i) {
    switch (i.type) {
      //视频
      case 2:

//        _controller = VideoPlayerController.network(i.content);
        return Row(
          key: ValueKey(i),
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Expanded(
                child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                SizedBox(
                  width: ScreenUtil().setWidth(19),
                ),
                CircleAvatar(
                  radius: ScreenUtil().setWidth(25),
//child: FadeInImage.assetNetwork(placeholder: "assets/ab.png", image: widget.followdata==null?widget.url:widget.followdata.headimgurl,),
                  backgroundImage: avatar(),
                ),
                Expanded(
                    child: GestureDetector(
                  child: Bubble(
                      margin: BubbleEdges.only(top: 10),
                      nip: BubbleNip.leftTop,
                      color: Color(0xff8DFA69),
                      child: v(i)
//                              videoView()
//                                  Container(width: 100,height: 200,child:videoView() ,)

//                              Padding(
//                                padding: const EdgeInsets.all(10.0),
//                                child: AspectRatioVideo(_controller),
//                              )
//          Image.asset("assets/ab.png",
//              width: ScreenUtil().setWidth(50),
//              height: ScreenUtil().setWidth(50)),
                      ),
                  onTap: () {
                    NaviUtil.push(this.context, VideoPage(i.data));
                  },
                )),
                SizedBox(
                  width: ScreenUtil().setWidth(15),
                ),
              ],
            )),
            Container(
              width: 93,
              height: 50,
              alignment: Alignment.center,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  GestureDetector(
                    child: Image.asset(
                      "assets/assist/xiangshang.png",
                      width: ScreenUtil().setWidth(20),
                      height: ScreenUtil().setWidth(20),
                    ),
                    onTap: () {
//                      print("${list.indexOf(i)}");
                      up(widget.info.indexOf(i));
                    },
                  ),
                  SizedBox(
                    width: ScreenUtil().setWidth(8),
                  ),
                  GestureDetector(
                    child: Image.asset(
                      "assets/assist/xiala.png",
                      width: ScreenUtil().setWidth(20),
                      height: ScreenUtil().setWidth(20),
                    ),
                    onTap: () {
                      down(widget.info.indexOf(i));
                    },
                  ),
                  SizedBox(
                    width: ScreenUtil().setWidth(8),
                  ),
                  GestureDetector(
                    child: Image.asset(
                      "assets/assist/guanbi1.png",
                      width: ScreenUtil().setWidth(20),
                      height: ScreenUtil().setWidth(20),
                    ),
                    onTap: () {
                      delete(widget.info.indexOf(i));
                    },
                  ),
                ],
              ),
            )
          ],
        );
        break;
//图片
      case 1:
        return Row(
          key: ValueKey(i),
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Expanded(
                child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                SizedBox(
                  width: ScreenUtil().setWidth(19),
                ),
                CircleAvatar(
                  radius: ScreenUtil().setWidth(25),
//                  child: FadeInImage.assetNetwork(placeholder: "assets/ab.png", image: widget.followdata==null?widget.url:widget.followdata.headimgurl),
                  backgroundImage: avatar(),
                ),
                Expanded(
                    child: GestureDetector(
                  child: Bubble(
                      margin: BubbleEdges.only(top: 10),
                      nip: BubbleNip.leftTop,
                      color: Color(0xff8DFA69),
                      child: i.data.startsWith("http")
                          ? Image.network(i.data)
                          : Image.file(File(i.data))
//          Image.asset("assets/ab.png",
//              width: ScreenUtil().setWidth(50),
//              height: ScreenUtil().setWidth(50)),
                      ),
                  onTap: () {

                     rebuildImageList();


                    NaviUtil.push(
                        this.context,
                        PhotoViewGalleryScreen(
                          images: images,
                          index: 0,
                        ));
                  },
                )),
                SizedBox(
                  width: ScreenUtil().setWidth(15),
                ),
              ],
            )),
            Container(
              width: 93,
              height: 50,
              alignment: Alignment.center,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  GestureDetector(
                    child: Image.asset(
                      "assets/assist/xiangshang.png",
                      width: ScreenUtil().setWidth(20),
                      height: ScreenUtil().setWidth(20),
                    ),
                    onTap: () {
                      print("${widget.info.indexOf(i)}");
                      up(widget.info.indexOf(i));
                    },
                  ),
                  SizedBox(
                    width: ScreenUtil().setWidth(8),
                  ),
                  GestureDetector(
                    child: Image.asset(
                      "assets/assist/xiala.png",
                      width: ScreenUtil().setWidth(20),
                      height: ScreenUtil().setWidth(20),
                    ),
                    onTap: () {
                      down(widget.info.indexOf(i));
                    },
                  ),
                  SizedBox(
                    width: ScreenUtil().setWidth(8),
                  ),
                  GestureDetector(
                    child: Image.asset(
                      "assets/assist/guanbi1.png",
                      width: ScreenUtil().setWidth(20),
                      height: ScreenUtil().setWidth(20),
                    ),
                    onTap: () {
                      delete(widget.info.indexOf(i));
                    },
                  ),
                ],
              ),
            )
          ],
        );

        break;
//文字
      case 3:
        return Row(
          key: ValueKey(i),
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Expanded(
                child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                SizedBox(
                  width: ScreenUtil().setWidth(19),
                ),
                CircleAvatar(
                  radius: ScreenUtil().setWidth(25),
//                  child: FadeInImage.assetNetwork(placeholder: "assets/ab.png", image: widget.followdata==null?widget.url:widget.followdata.headimgurl),
//                  backgroundImage: NetworkImage(widget.followdata==null?widget.url:widget.followdata.headimgurl),
                  backgroundImage: avatar(),
                ),
                Expanded(
                    child: GestureDetector(
                  child: Bubble(
                      margin: BubbleEdges.only(top: 10),
                      nip: BubbleNip.leftTop,
                      color: Color(0xff8DFA69),
                      child: Text("${i.data}")
//          Image.asset("assets/ab.png",
//              width: ScreenUtil().setWidth(50),
//              height: ScreenUtil().setWidth(50)),
                      ),
//        onTap: () {
//          NaviUtil.push(
//              this.context,   PhotoViewGalleryScreen(images: images,index: 0,));
//        },
                      onLongPress: (){

                        ClipboardData c = ClipboardData(text: i.data);
                        Clipboard.setData(c);
                        Toast.show(msg: "文案已复制");

                      },

                )),
                SizedBox(
                  width: ScreenUtil().setWidth(15),
                ),
              ],
            )),
            Container(
              width: 93,
              height: 50,
              alignment: Alignment.center,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  GestureDetector(
                    child: Image.asset(
                      "assets/assist/xiangshang.png",
                      width: ScreenUtil().setWidth(20),
                      height: ScreenUtil().setWidth(20),
                    ),
                    onTap: () {
                      print("${widget.info.indexOf(i)}");
                      up(widget.info.indexOf(i));
                    },
                  ),
                  SizedBox(
                    width: ScreenUtil().setWidth(8),
                  ),
                  GestureDetector(
                    child: Image.asset(
                      "assets/assist/xiala.png",
                      width: ScreenUtil().setWidth(20),
                      height: ScreenUtil().setWidth(20),
                    ),
                    onTap: () {
                      down(widget.info.indexOf(i));
                    },
                  ),
                  SizedBox(
                    width: ScreenUtil().setWidth(8),
                  ),
                  GestureDetector(
                    child: Image.asset(
                      "assets/assist/guanbi1.png",
                      width: ScreenUtil().setWidth(20),
                      height: ScreenUtil().setWidth(20),
                    ),
                    onTap: () {
                      delete(widget.info.indexOf(i));
                    },
                  ),
                ],
              ),
            )
          ],
        );
        break;

      case 4:
        return Row(
          key: ValueKey(i),
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Expanded(
                child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                SizedBox(
                  width: ScreenUtil().setWidth(19),
                ),
                CircleAvatar(
                  radius: ScreenUtil().setWidth(25),
//                   child: FadeInImage.assetNetwork(placeholder: "assets/ab.png", image: widget.followdata==null?widget.url:widget.followdata.headimgurl),
                  backgroundImage: avatar(),
                ),
                Expanded(
                    child: GestureDetector(
                  child: Bubble(
                      margin: BubbleEdges.only(top: 10),
                      nip: BubbleNip.leftTop,
                      color: Color(0xff8DFA69),
                      child: Container(
                        width: ScreenUtil().setWidth(215),
                        height: ScreenUtil().setHeight(80),
                        child: Row(
                          children: <Widget>[
                            Container(
                              width: ScreenUtil().setWidth(188),
                              height: ScreenUtil().setHeight(80),
                              decoration: redButtonStyleWithBorder,
                              alignment: Alignment.center,
                              padding: EdgeInsets.all(ScreenUtil().setWidth(5)),
                              child: 
                              Row(
                              children: <Widget>[
                                
                                Image.network((BussinussUtil.parseLink(i.data, "img_url") as String),width: ScreenUtil().setWidth(50),height: ScreenUtil().setHeight(50),),

                                Expanded(child: Column(
                                  mainAxisAlignment:
                                  MainAxisAlignment.spaceBetween,
                                  children: <Widget>[
                                    Text(
                                      (BussinussUtil.parseLink(i.data, "title") as String),
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                    Row(
                                      mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                      children: <Widget>[
                                        Text((BussinussUtil.parseLink(i.data, "y") as String),style: TextStyle(color: Colors.grey),)
                                        ,

                                      ],
                                    )
                                  ],
                                ))

                                
                              ],
                              
                              )
                             ,
                            ),
//                            SizedBox(
//                              width: ScreenUtil().setWidth(2),
//                            ),
//                            Container(
//                              width: ScreenUtil().setWidth(65),
//                              height: ScreenUtil().setHeight(60),
//                              alignment: Alignment.center,
//                              decoration: redButtonStyleWithBorder,
//                              padding: EdgeInsets.symmetric(
//                                  vertical: ScreenUtil().setHeight(5)),
//                              child: Column(
//                                mainAxisAlignment:
//                                    MainAxisAlignment.spaceBetween,
//                                children: <Widget>[
//                                  Image.asset(
//                                    "assets/ab.png",
//                                    width: ScreenUtil().setWidth(24),
//                                    height: ScreenUtil().setHeight(24),
//                                  ),
//                                  Text("二维码")
//                                ],
//                              ),
//                            )
                          ],
                        ),
                      )
//          Image.asset("assets/ab.png",
//              width: ScreenUtil().setWidth(50),
//              height: ScreenUtil().setWidth(50)),
                      ),
//        onTap: () {
//          NaviUtil.push(
//              this.context,   PhotoViewGalleryScreen(images: images,index: 0,));
//        },
                )),
                SizedBox(
                  width: ScreenUtil().setWidth(15),
                ),
              ],
            )),
            Container(
              width: 93,
              height: 50,
              alignment: Alignment.center,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  GestureDetector(
                    child: Image.asset(
                      "assets/assist/xiangshang.png",
                      width: ScreenUtil().setWidth(20),
                      height: ScreenUtil().setWidth(20),
                    ),
                    onTap: () {
                      print("${widget.info.indexOf(i)}");
                      up(widget.info.indexOf(i));
                    },
                  ),
                  SizedBox(
                    width: ScreenUtil().setWidth(8),
                  ),
                  GestureDetector(
                    child: Image.asset(
                      "assets/assist/xiala.png",
                      width: ScreenUtil().setWidth(20),
                      height: ScreenUtil().setWidth(20),
                    ),
                    onTap: () {
                      down(widget.info.indexOf(i));
                    },
                  ),
                  SizedBox(
                    width: ScreenUtil().setWidth(8),
                  ),
                  GestureDetector(
                    child: Image.asset(
                      "assets/assist/guanbi1.png",
                      width: ScreenUtil().setWidth(20),
                      height: ScreenUtil().setWidth(20),
                    ),
                    onTap: () {
                      delete(widget.info.indexOf(i));
                    },
                  ),
                ],
              ),
            )
          ],
        );
        break;
    }
  }

  void rebuildImageList(){
    images.clear();
    for(int i=0;i<widget.info.length;i++){
      if(widget.info[i].type==1){
        images.add(widget.info[i].data);
      }
    }
  }
  ImageProvider avatar(){
    if(widget.from!=null){
      return NetworkImage(Constants.memberInfoEntity.data.headimgurl);
    }
//    if(widget.from=="tianjiasucai"){
//
//
//
//    }

    else{

      if(widget.followdata!=null){
        return NetworkImage(widget.followdata.headimgurl);

      }else{

        return AssetImage("assets/assist/aplus.png");

      }


    }


  }

  
  String _retrieveDataError;
//  Future<void> retrieveLostData() async {
//    final LostData response = await _picker.getLostData();
//    if (response.isEmpty) {
//      return;
//    }
//    if (response.file != null) {
//      if (response.type == RetrieveType.video) {
//        isVideo = true;
//        await _playVideo(response.file);
//      } else {
//        isVideo = false;
//        setState(() {
//          _imageFile = response.file;
//        });
//      }
//    } else {
//      _retrieveDataError = response.exception.code;
//    }
//  }

//  Widget videoView() {
//    Fluttertoast.showToast(msg: "${_controller.value.initialized}");
//    return _controller.value.initialized
//        ? AspectRatio(
//            aspectRatio: _controller.value.aspectRatio,
////      aspectRatio: 0.65,
//            child: VideoPlayer(_controller),
//          )
//        : Container();
//  }

//  Widget _previewVideo() {
//    final Text retrieveError = _getRetrieveErrorWidget();
//    if (retrieveError != null) {
//      return retrieveError;
//    }
//    if (_controller == null) {
//      return const Text(
//        'You have not yet picked a video',
//        textAlign: TextAlign.center,
//      );
//    }
//    return Padding(
//      padding: const EdgeInsets.all(10.0),
//      child: AspectRatioVideo(_controller),
//    );
//  }

//  Text _getRetrieveErrorWidget() {
//    if (_retrieveDataError != null) {
//      final Text result = Text(_retrieveDataError);
//      _retrieveDataError = null;
//      return result;
//    }
//    return null;
//  }

//  Widget _previewImage() {
//    final Text retrieveError = _getRetrieveErrorWidget();
//    if (retrieveError != null) {
//      return retrieveError;
//    }
//    if (_imageFile != null) {
//      if (kIsWeb) {
//        // Why network?
//        // See https://pub.flutter-io.cn/packages/image_picker#getting-ready-for-the-web-platform
//        return Image.network(_imageFile.path);
//      } else {
//        return Image.file(File(_imageFile.path));
//      }
//    } else if (_pickImageError != null) {
//      return Text(
//        'Pick image error: $_pickImageError',
//        textAlign: TextAlign.center,
//      );
//    } else {
//      return const Text(
//        'You have not yet picked an image.',
//        textAlign: TextAlign.center,
//      );
//    }
//  }
  Future<bool> started(GroupPlanListDataTimeDataTaskSendInfo detailTemp) async {
//    _controller = VideoPlayerController.network(
//        "https://www.runoob.com/try/demo_source/mov_bbb.mp4");
//      ..initialize().then((_) {
//        // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
//        setState(() {});
//      });
//    await _controller.initialize();
//    await list[index].controller.initialize();
    await detailTemp.controller.initialize();
//    await _controller.play();
//    startedPlaying = true;
    return true;
  }

  Widget v(GroupPlanListDataTimeDataTaskSendInfo detailTemp) {
    return FutureBuilder<bool>(
      future: started(detailTemp),
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
        if (snapshot.data == true) {
          return 
            Stack(
              
              children: <Widget>[
             
                AspectRatio(
                  aspectRatio: detailTemp.controller.value.aspectRatio,
                  child: VideoPlayer(detailTemp.controller),
                ),
                Positioned(child: Image.asset("assets/assist/shipin.png",width: ScreenUtil().setWidth(30),height: ScreenUtil().setHeight(30),),left: ScreenUtil().setWidth(85),top: ScreenUtil().setHeight(85),)


                
                
              ],
              
            )
            
            ;
        } else {
          return const Text('正在加载视频');
        }
      },
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose

    for (GroupPlanListDataTimeDataTaskSendInfo detailTemp in widget.info) {
      if (detailTemp.controller != null) {
        detailTemp.controller.dispose();
      }
    }
    super.dispose();
  }

  ///保存选项
  void showSaveDialog() {
    showDialog(
        context: context,
        builder: (c) {
          return SaveDialogWidget(
            info: widget.info,
          );
        });
  }

  void buildMenu() {}

  bool link = true;

  ///选择产品
  void _showBottomSheet(bool link) {
    showModalBottomSheet(
        isScrollControlled: true,
        context: this.context,
        builder: (bui) {
          if (link) {
            return SizedBox(
              height: ScreenUtil().setHeight(650),
              child: ProductList(link: link, linkcall: linkCall),
            );
          } else {
            return SizedBox(
              height: ScreenUtil().setHeight(650),
              child: ProductList(link: link, call: relatedproductCall),
            );
          }
        });
  }

  String goodsId = "";
  void relatedproductCall(String relatedproduct) {
    goodsId = relatedproduct;
  }

  void linkCall(String id, String y, String linkTitle, String imgurl) {
//    i=秒杀id&t=1&y=3
    GroupPlanListDataTimeDataTaskSendInfo info =
        GroupPlanListDataTimeDataTaskSendInfo();
    String data = "i=" + id + "&t=1" + "&y=" + y+"&title="+linkTitle+"&img_url="+imgurl;//传到服务器的时候用split，只将前面的传上去就可
    info.data = data;
    info.type = 4;
    int temp = 0;
    for (int i = 0; i < widget.info.length; i++) {
      if (widget.info[i].index > temp) {
        temp = widget.info[i].index;
      }
    }
    info.index = temp + 1;
//    info.linkTitle = linkTitle;
//    info.linkPrice = price;
    widget.info.add(info);

    setState(() {});
  }

  void _showChoosePost() {
    DialogUtil.showdialog1(
        this.context,
        Container(
          width: ScreenUtil().setWidth(323),
          height: ScreenUtil().setHeight(264),
          padding: EdgeInsets.only(
              left: ScreenUtil().setWidth(45),
              right: ScreenUtil().setWidth(45),
              top: ScreenUtil().setHeight(52),
              bottom: ScreenUtil().setHeight(36)),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                children: <Widget>[
                  Container(
                    width: ScreenUtil().setWidth(109),
                    height: ScreenUtil().setHeight(90),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Color(0xffF94F68),
                        borderRadius:
                            BorderRadius.circular(ScreenUtil().setHeight(4))),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Image.asset(
                          "assets/publish.png",
                          width: ScreenUtil().setWidth(24),
                          height: ScreenUtil().setHeight(24),
                        ),
                        SizedBox(
                          height: ScreenUtil().setHeight(15),
                        ),
                        Text(
                          "立即发布",
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: ScreenUtil().setSp(16)),
                        )
                      ],
                    ),
                  ),
                  Expanded(child: Text("")),
                  Container(
                    width: ScreenUtil().setWidth(109),
                    height: ScreenUtil().setHeight(90),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Color(0xffF94F68),
                        borderRadius:
                            BorderRadius.circular(ScreenUtil().setHeight(4))),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Image.asset(
                          "assets/set.png",
                          width: ScreenUtil().setWidth(24),
                          height: ScreenUtil().setHeight(24),
                        ),
                        SizedBox(
                          height: ScreenUtil().setHeight(15),
                        ),
                        Text(
                          "设置计划",
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: ScreenUtil().setSp(16)),
                        )
                      ],
                    ),
                  ),
                ],
              ),
              GestureDetector(
                child: Container(
                  width: ScreenUtil().setWidth(161),
                  height: ScreenUtil().setHeight(40),
                  alignment: Alignment.center,
                  decoration: redButtonStyleWithBorder,
                  child: Text(
                    "取消",
                    style: TextStyle(
                        color: Color(0xffFA657B),
                        fontSize: ScreenUtil().setSp(14)),
                  ),
                ),
                onTap: () {
                  NaviUtil.pop(this.context);
                },
              )
            ],
          ),
        ),
        ScreenUtil().setHeight(264));
  }

  void _showProductDialog() {
    showModalBottomSheet(context: this.context, builder: (c) {});
  }

  ///保存发布成功弹窗
  void _showPostOrSaveSuccess(String string) {
    DialogUtil.showdialog1(
        this.context,
        Container(
          width: ScreenUtil().setWidth(323),
          height: ScreenUtil().setHeight(264),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              SizedBox(
                height: ScreenUtil().setHeight(61),
              ),
              Image.asset(
                "assets/ab.png",
                width: ScreenUtil().setWidth(59),
                height: ScreenUtil().setHeight(59),
              ),
              SizedBox(
                height: ScreenUtil().setHeight(16),
              ),
              Text(
                "${string}成功",
                style: TextStyle(
                    color: Color(0xff101010),
                    fontSize: ScreenUtil().setSp(16),
                    fontWeight: FontWeight.bold),
              ),
              SizedBox(
                height: ScreenUtil().setHeight(38),
              ),
              GestureDetector(
                child: Container(
                  width: ScreenUtil().setWidth(161),
                  height: ScreenUtil().setHeight(40),
                  alignment: Alignment.center,
                  decoration: redButtonStyleWithBorder,
                  child: Text(
                    "确认",
                    style: TextStyle(
                        color: Color(0xffFA657B),
                        fontSize: ScreenUtil().setSp(14)),
                  ),
                ),
                onTap: () {
                  NaviUtil.pop(this.context);
                },
              )
            ],
          ),
        ),
        ScreenUtil().setHeight(264));
  }
  void buildDownLoadList(){

    for(int i=0;i<widget.info.length;i++){

      if(widget.info[i].type==1){
        //图片
         downloadList.add(Download(widget.info[i].data, "1"));

      }else if(widget.info[i].type==2){
        //视频
        downloadList.add(Download(widget.info[i].data, "2"));

      }


    }


  }

  void generateUpload(String url,bool image){
    if(!image){

      GroupPlanListDataTimeDataTaskSendInfo info =
      GroupPlanListDataTimeDataTaskSendInfo();
      info.data = url;
      info.type = 2;
      int temp = 0;
      for (int i = 0; i < widget.info.length; i++) {
        if (widget.info[i].index > temp) {
          temp = widget.info[i].index;
        }
      }
      info.index = temp + 1;
      info.setController(VideoPlayerController.network(url));

      widget.info.add(info);

      images.add(info.data);

    }else{
      GroupPlanListDataTimeDataTaskSendInfo info =
      GroupPlanListDataTimeDataTaskSendInfo();
      info.type = 1;
      info.data = url;
      int temp = 0;
//      File  f = File(pickedFile.path);
      for (int i = 0; i < widget.info.length; i++) {
        if (widget.info[i].index > temp) {
          temp = widget.info[i].index;
        }
      }
      info.index = temp + 1;
      widget.info.add(info);


    }
  }
  void requestUpload(File file,bool image) async{

//    EasyLoading.showSuccess("正在加载……");

       DialogUtil.showloadingdialog(context);
      try {
//        Map<String, dynamic> map = Map<String, dynamic>();



//      map["keyword"] = widget.search;
//      map["page"] = currentPage;

        Map<String, dynamic> map1 = await HttpClient.requestUpload(
            file,image);
//
        UploadEntity loginEntity = new UploadEntity();

        loginEntity = uploadEntityFromJson(loginEntity, map1);

        DialogUtil.pop(context);
        if (loginEntity.code == null || loginEntity.code != 200) {
//        Fluttertoast.showToast(msg: "null");
          Toast.show(msg: loginEntity.msg);

          return;
        }
        if (loginEntity.code == 200) {
//        Toast.show(msg: "创建成功");
//        NaviUtil.pop(this.context);

        generateUpload(loginEntity.data, image);



          setState(() {});
        }
      } catch (e) {
        print(e.toString());
        DialogUtil.pop(context);
      }

  }





}

typedef void OnPickImageCallback(
    double maxWidth, double maxHeight, int quality);

class AspectRatioVideo extends StatefulWidget {
  AspectRatioVideo(this.controller);

  final VideoPlayerController controller;

  @override
  AspectRatioVideoState createState() => AspectRatioVideoState();
}

class AspectRatioVideoState extends State<AspectRatioVideo> {
  VideoPlayerController get controller => widget.controller;
  bool initialized = false;

  void _onVideoControllerUpdate() {
    if (!mounted) {
      return;
    }
    if (initialized != controller.value.initialized) {
      initialized = controller.value.initialized;
      setState(() {});
    }
  }

  @override
  void initState() {
    super.initState();
    controller.addListener(_onVideoControllerUpdate);
  }

  @override
  void dispose() {
    controller.removeListener(_onVideoControllerUpdate);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (initialized) {
      return Center(
        child: AspectRatio(
          aspectRatio: controller.value?.aspectRatio,
          child: VideoPlayer(controller),
        ),
      );
    } else {
      return Container();
    }
  }





}

class SaveDialogWidget extends StatefulWidget {
  List<GroupPlanListDataTimeDataTaskSendInfo> info = null;

  SaveDialogWidget({this.info});
  @override
  _SaveDialogWidgetState createState() => _SaveDialogWidgetState();
}

class _SaveDialogWidgetState extends State<SaveDialogWidget> {
//  String goodsId = ""; //保存时的关联商品id

  List<DropdownMenuItem<String>> sortItems = [];
  String selectedSort = '排序';

  TextEditingController controller = TextEditingController();

  BuildContext context;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) { requestMaterialType();});

  }

  @override
  Widget build(BuildContext context) {
    this.context = context;
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Container(
        margin: EdgeInsets.only(
            left: ScreenUtil().setWidth(44), top: ScreenUtil().setHeight(50)),
        padding: EdgeInsets.only(
            left: ScreenUtil().setWidth(29),
            right: ScreenUtil().setWidth(29),
            top: ScreenUtil().setHeight(29)),
        width: ScreenUtil().setWidth(323),
        height: ScreenUtil().setHeight(420),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(ScreenUtil().setWidth(4))),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              "任务名",
              style: TextStyle(
                  color: Color(0xff101010),
                  fontSize: ScreenUtil().setSp(16),
                  fontWeight: FontWeight.bold),
            ),
            SizedBox(
              height: ScreenUtil().setHeight(21),
            ),
            Container(
              width: ScreenUtil().setWidth(261),
              height: ScreenUtil().setHeight(40),
              child: TextField(
                decoration: InputDecoration(border: InputBorder.none),
                controller: this.controller,
              ),
              decoration: BoxDecoration(
                  border: Border.all(color: Color(0xffDCDFE6)),
                  borderRadius:
                      BorderRadius.circular(ScreenUtil().setWidth(4))),
            ),
            SizedBox(
              height: ScreenUtil().setHeight(21),
            ),
            Text(
              "任务分类",
              style: TextStyle(
                  color: Color(0xff101010),
                  fontSize: ScreenUtil().setSp(16),
                  fontWeight: FontWeight.bold),
            ),
            SizedBox(
              height: ScreenUtil().setHeight(21),
            ),
            GestureDetector(
              child: Container(
                width: ScreenUtil().setWidth(261),
                height: ScreenUtil().setHeight(40),
                child: MenuWidget(
                  this.sortItems,
                  this.selectedSort,
                  call: menuCall,
                ),
                decoration: BoxDecoration(
                    border: Border.all(color: Color(0xffDCDFE6)),
                    borderRadius:
                        BorderRadius.circular(ScreenUtil().setWidth(4))),
              ),
              onTap: () {},
            ),

//            MenuWidget(widget.sortItems, widget.selectedSort),
            SizedBox(
              height: ScreenUtil().setHeight(21),
            ),
            Text(
              "关联商品",
              style: TextStyle(
                  color: Color(0xff101010),
                  fontSize: ScreenUtil().setSp(16),
                  fontWeight: FontWeight.bold),
            ),
            SizedBox(
              height: ScreenUtil().setHeight(21),
            ),
            GestureDetector(
              child: Container(
                width: ScreenUtil().setWidth(261),
                height: ScreenUtil().setHeight(40),
                padding: EdgeInsets.only(
                    left: ScreenUtil().setWidth(10),
                    right: ScreenUtil().setWidth(10)),
                decoration: BoxDecoration(
                    border: Border.all(color: Color(0xffDCDFE6)),
                    borderRadius:
                        BorderRadius.circular(ScreenUtil().setWidth(4))),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text(
                      "${this.productListData==null?"选择商品":this.productListData.name}",
                      style: TextStyle(
                          color: Color(0xff101010),
                          fontSize: ScreenUtil().setSp(14)),
                    ),
                    Image.asset(
                      "assets/assist/jiantou.png",
                      width: ScreenUtil().setWidth(14),
                      height: ScreenUtil().setHeight(14),
                    )
                  ],
                ),
              ),
              onTap: () {
                _showBottomSheet(false);
              },
            ),
            SizedBox(
              height: ScreenUtil().setHeight(21),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                GestureDetector(
                  child: Container(
                    width: ScreenUtil().setWidth(119),
                    height: ScreenUtil().setHeight(40),
                    decoration: redButtonStyleWithBorder,
                    alignment: Alignment.center,
                    child: Text(
                      "取消",
                      style: TextStyle(
                          color: Color(0xffFA657B),
                          fontSize: ScreenUtil().setSp(16)),
                    ),
                  ),
                  onTap: () {
                    NaviUtil.pop(context);
                  },
                ),
                GestureDetector(
                  child: Container(
                    width: ScreenUtil().setWidth(119),
                    height: ScreenUtil().setHeight(40),
                    decoration: redButtonStyle,
                    alignment: Alignment.center,
                    child: Text(
                      "确定",
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: ScreenUtil().setSp(16)),
                    ),
                  ),
                  onTap: () {
                    if (controller.text.toString().isEmpty) {
                      Toast.show(msg: "请填写任务名");
                      return;
                    }
                    if (this.productListData == null) {
                      Toast.show(msg: "请选择关联商品");
                      return;
                    }
                    if (this.typeId.isEmpty) {
                      Toast.show(msg: "请选择分类");
                      return;
                    }
                    NaviUtil.pop(context);
                    requestSaveMaterial();
                  },
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

  void menuCall(String selectSort) {
    for (int i = 0; i < sortItems.length; i++) {
      if (sortItems[i].value == selectSort) {
        typeId = materialTypeEntity.data[i].id.toString();
      }
    }
  }

  void _showBottomSheet(bool link) {
    showModalBottomSheet(
        isScrollControlled: true,
        context: this.context,
        builder: (bui) {
          if (link) {
            return SizedBox(
              height: ScreenUtil().setHeight(650),
              child: ProductList(link: link, linkcall: linkCall),
            );
          } else {
            return SizedBox(
              height: ScreenUtil().setHeight(650),
              child: ProductList(link: link, call: productListCall),
            );
          }
        });
  }

  JjhwProductListData productListData;
  void productListCall(JjhwProductListData relatedproduct) {
    this.productListData = relatedproduct;
    setState(() {

    });
  }

  void linkCall(String id, String y, String linkTitle, String price) {
//    i=秒杀id&t=1&y=3
    GroupPlanListDataTimeDataTaskSendInfo info =
        GroupPlanListDataTimeDataTaskSendInfo();
    String data = "i=" + id + "&t=1" + "&y=" + y;
    info.data = data;
    info.type = 4;
    int temp = 0;
    for (int i = 0; i < widget.info.length; i++) {
      if (widget.info[i].index > temp) {
        temp = widget.info[i].index;
      }
    }
    info.index = temp + 1;
    info.linkTitle = linkTitle;
    info.linkPrice = price;
    widget.info.add(info);

    setState(() {});
  }

  List<int> type = List();
  List<String> content = List();
  List<int> sort = List();
  void buildList() {
    type.clear();
    content.clear();
    sort.clear();
    for (int i = 0; i < widget.info.length; i++) {
      type.add(widget.info[i].type);
      if(widget.info[i].type==4){
        if(widget.info[i].data.contains("title=")){
          content.add(widget.info[i].data.split("&title")[0]);
        }else{
          content.add(widget.info[i].data);
        }

      }else{
        content.add(widget.info[i].data);
      }

      sort.add(widget.info.length - i);
    }
  }


  String typeId = "";
  void requestSaveMaterial() async {
//    EasyLoading.showSuccess("正在加载……");
//   DialogUtil.showloadingdialog(context);

    try {
      Map<String, dynamic> map = Map<String, dynamic>();

      buildList();
//      map["member_id"] = Constants.memberInfoEntity.data.memberId;
      map["member_id"] = Constants.memberInfoEntity.data.memberId;
      map["name"] = controller.text.toString();
      map["type"] = type;
      map["content"] = content;
      map["sort"] = sort;
      map["goods_id"] = this.productListData.id.toString();
      map["type_id"] = typeId;

//      map["keyword"] = widget.search;
//      map["page"] = currentPage;

      Map<String, dynamic> map1 = await HttpClient.requestLogin(
          Config.requestApi + 'light/task/add',
          data: map);
//
      CommonResultEntity loginEntity = new CommonResultEntity();

      loginEntity = commonResultEntityFromJson(loginEntity, map1);

//      DialogUtil.pop(context);
      if (loginEntity.code == null || loginEntity.code != 200) {
//        Fluttertoast.showToast(msg: "null");
        Toast.show(msg: loginEntity.msg);

        return;
      }
      if (loginEntity.code == 200) {
        Toast.show(msg: "创建成功，审核后才可发布");
        NaviUtil.pop(this.context);


//        NaviUtil.pop(this.context);
        setState(() {});
      }
    } catch (e) {
      print(e.toString());
//      NaviUtil.pop(context);
    }
  }

  MaterialTypeEntity materialTypeEntity = null;
  void requestMaterialType() async {
//    DialogUtil.showloadingdialog(context);
    try {
      Map<String, dynamic> map = Map<String, dynamic>();

//      map["member_id"] = Constants.memberInfoEntity.data.memberId;
//      map["type_id"] = "";
//      map["keyword"] = "";
//      map["page"] = currentPage;

      Map<String, dynamic> map1 = await HttpClient.requestLogin(
          Config.requestApi + 'light/task/type',
          data: map);

//      v.dismiss();
      MaterialTypeEntity loginEntity = new MaterialTypeEntity();

      loginEntity = materialTypeEntityFromJson(loginEntity, map1);

//      DialogUtil.pop(context);
      if (loginEntity.code == null || loginEntity.code != 200) {
//        Fluttertoast.showToast(msg: "null");
        Toast.show(msg: loginEntity.msg);

        return;
      }
      if (loginEntity.code == 200) {
//        Toast.show(msg: "创建成功");
//        NaviUtil.pop(this.context);



        materialTypeEntity = loginEntity;
        for (int i = 0; i < materialTypeEntity.data.length; i++) {
          sortItems.add(DropdownMenuItem(
            child: Text("${materialTypeEntity.data[i].name}"),
            value: "${materialTypeEntity.data[i].name}",
          ));
        }
        selectedSort = sortItems[0].value;
        typeId = materialTypeEntity.data[0].id.toString();
        setState(() {});
      }
    } catch (e) {
      print(e.toString());
//      DialogUtil.pop(context);
    }
  }
}
